<?php
namespace app\mobile\controller;

use think\Db;
use think\Controller;
use think\Request;
use think\Session;
use think\Cookie;

class Details extends Controller
{ 
    private $uid;
    public function _initialize()
    {
      !( empty(cookie::get('loginid')) && empty(session::get('user')) )? $uid = '' : 
        (!empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid'));
      $this->uid = $uid;
    }
    
    /* 看书 */
    public function readbook($id)
    { 
      // 未登录|未购买 试读前三章
      if($this->uid){
        $info = db('orders')->where('cid',$id)->where('uid',$uid)->where('status',1)->find();
      }else{
        $info = null;
      }

      // 点击率 +1
      $hit = db('data')->where('id','=',$id)->setInc('hot');
      // 获取文章信息
      $data = db('article')->field('cid',true)->where('cid','=',$id)->select();
      if (!empty($data)) {
        if(!empty($info)){
          $list = db('article')->field('cid',true)->where('cid','=',$id)->paginate(1);
        }else{
          $data = db('article')->field('cid',true)->where('cid','=',$id)->limit(3)->select();
          foreach ($data as $k => $v) { $ids[] = $v['id']; }
          $list = db('article')->field('cid',true)->where('id','in',$ids)->paginate(1);
        }
        
        $page = $list->render();
      }else{ $list = ''; $page='';}

      // 书本信息
       $book = db('data')->field(['name','id'])->where('id',$id)->find();

      return view('details/content',[
          'title'=>$book['name'],
          'data'=>$data,
          'list'=>$list,
          'book'=>$book,
          'info'=>$info,
          'page'=>$page
        ]);
    }

    /* 目录 */
    public function showdir(Request $request)
    { 
      $res = $request->param();

      // 顺序倒序
      empty($res['where'])? $where='id asc' : $where='id desc';
      // 获取目录信息
      // 未登录|未购买 试读前三章
      if($this->uid){
        $info = db('orders')->where('cid',$id)->where('uid',$uid)->where('status',1)->find();
      }else{
        $info = null;
      }
      $list = db('article')->field(['name'])->where('cid','=',$res['id'])->order($where)->select();

      // 获取分类信息
      $class = db('category as c,s75_data as d')->field(['c.id cid','d.id','c.name','d.name dname'])
        ->where('c.id = d.cid')->where('d.id',$res['id'])->find();

      return view('details/dir',[
          'title'=>$class['dname'],
          'list'=>$list,
          'class'=>$class
        ]);
    }

    /* 详情 */
    public function read($id)
    {
      // 书本信息
      $data = db('data')->where('id',$id)->find();
      // 分类信息
      $two = db('category')->field(['id','pid','name'])->where('id','=',$data['cid'])->find();
      $one = db('category')->field(['id','name'])->where('id','=',$two['pid'])->find();
      // 订单信息
      !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
      $info = db('orders')->where('cid',$id)->where('uid',$uid)->find();
      if($info['status'] == 1){
         $info['desc'] = '已购买';
      }else{
         $info['desc'] = '立即购买';
      }
      // 目录信息
      $dir = db('article')->field('cid',true)->where('cid','=',$id)->select();
      $count_dir = count($dir);
      // 评论信息
      $comment = db('comment')->where('cid','=',$id)->select();
        $arr = [];
        foreach ($comment as $k => $v) { $arr[] = $v['uid']; }
        $cmtUser = db('user')->field(['icon','name','id'])->where('id','in',$arr)->select();
        // user 与 comment 合并
         $score = ''; $array = [];
         foreach ($comment as $k => $v) { 
            $comment[$k]['icon'] = ''; $comment[$k]['name'] = '';
            foreach ($cmtUser as $k1 => $v1) {
              if ($v1['id'] == $v['uid']) {
                $comment[$k]['icon'] =$v1['icon'];
                $comment[$k]['name'] =$v1['name'];
              }
            } 
            $array[] = $v['cmt'];
           
         }
         // 将关联评论放在该评论下
          foreach ($comment as $k => $v) {
            if ($v['gid']!=null) {
                $son[] = $v;
                $comment = array_diff_key($comment,[$k=>'']);
            }
         }
        if (!empty($son)) {
          foreach ($comment as $k => $v) {
               $comment[$k]['son'] = [];
              foreach ($son as $k1 => $v1) {
                if ($v['id']==$v1['gid']) { $comment[$k]['son'][] = $v1; }
              }
            }
        }

       // 统计得分 评论条数
      if (!empty($array)) { $score = number_format(array_sum($array)*2/count($array),1); }else{ $score = '暂无'; }
      $count_cmt = count($comment);
      


      // 同类热门(一级)
        // 遍历二级分类池
        $child = db('category')->field(['id'])->where('pid','=',$two['pid'])->select();
        foreach ($child as $k => $v) { $child[$k] = $v['id']; }
        // 查询书本信息
        $hot = db('data')->field(['id','name','author','face','hot','price'])->where('cid','in',$child)
              ->where('id','neq',$data['id'])->order('hot desc')->limit(4)->select();
      // 相关推荐
        // $like = db('data')->field(['id','name','author','face','price'])->where('tag','like','%'.$data['tag'].'%')
        // ->where('id','neq',$data['id'])->limit(4)->select();
        $like = db('data')->field(['id','name','author','face','hot','price'])->where('cid','in',$child)
         ->where('id','neq',$data['id'])->order('id desc')->limit(4)->select();
     // 历史记录
       // 存为历史记录
       // session::set('book',null); die;
        session::set('book.'.$data['id'], $data);
        $books = session::get('book');
        // 保留5条(不包含当前)
        if (count(session::get('book')) > 6) {
           array_shift($books);
        }   
        session::set('book',$books);
        // 倒序
        $books = array_reverse($books);

      $this->assign('uid',$uid);
      $this->assign('data',$data);
      $this->assign('one',$one);
      $this->assign('two',$two);
      $this->assign('info',$info);
      $this->assign('dir',$dir);
      $this->assign('count_dir',$count_dir);
      $this->assign('comment',$comment);
      $this->assign('count_cmt',$count_cmt);
      $this->assign('score',$score);
      $this->assign('hotdata',$hot);
      $this->assign('likedata',$like);
      $this->assign('books',$books);
      $this->assign('title',$data['name'].'全文阅读');

      return $this->fetch('details/index');
    }

    /* 评论 */
    public function comment(Request $request)
    { 
      $data = $request->post();
      $uid = $this->uid;

      if (empty($uid)) {
            $info['status'] = 'false';
            $info['info'] = '亲,请先登录哦';
      }else{
        $data['uid'] = $uid;
        $data['ctime'] = date('Y-m-d h:i:s');
        $res = db('comment')->insert($data); 

         if($res){
            $info['status'] = 'true';
            $info['info'] = '发表成功';
          }else{
            $info['status'] = 'false';
            $info['info'] = '阿偶出错了,过会再发吧';
          }
      }
      
          return json($info);
    }
  
    public function collect($id)
    {
        !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
         $data = [
            'uid'=>$uid,
            'cid'=>$id,
            'time'=>time()
        ];
        $res = Db::table('s75_collect')->where('cid',$id)->where('uid',$uid)->find();
        if($res){
                $info['status'] = 'false';
                $info['info'] = '你已经收藏过了';
        }else{
             $result = Db::table('s75_collect')->insert($data); 
              if($result>0) {
                $info['status'] = 'true';
                $info['info'] = '收藏成功';
              }else{
                $info['status'] = 'false';
                $info['info'] = '收藏失败';
              }
        }
        return json($info);
    }


    public function pay($id)
    {
       !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
       $res = Db::table('s75_data')->field(['price'])->where('id',$id)->find();
       $info = [
            'uid'=>$uid,
            'cid'=>$id,
            'order_number'=>date('Ymdhis'),
            'status'=>'1',
            'otime'=>time(),
            'pay_money'=>$res['price']
       ];
       $result = Db::table('s75_orders')->where('cid',$id)->where('status',1)->where('uid',$uid)->find();
       if($result){
                $info['status'] = 'false';
                $info['info'] = '你已经购买过了';
       }else{
          $resul = Db::table('s75_orders')->where('cid',$id)->where('status',0)->where('uid',$uid)->find();
          if($resul){
          $inf = [
            'status'=>'1',
            'otime'=>time()
           ];
             $data = Db::table('s75_orders')->where('cid',$id)->update($inf);
             $info['status'] = 'true';
             $info['info'] = '购买成功';
          }else{
            $data = Db::table('s75_orders')->insert($info);
            $info['status'] = 'true';
            $info['info'] = '购买成功';
          }
         
       }
       return json($info);

       
    }

    public function buy($id)
    {
        !empty(session::get('user'))? $uid = session::get('user.id') : $uid = cookie::get('loginid');
        $res1 = Db::table('s75_data')->field(['price'])->where('id',$id)->find();
        $data = [
            'uid'=>$uid,
            'cid'=>$id,
            'order_number'=>date('Ymdhis'),
            'status'=>'0',
            'pay_money'=>$res1['price'],
            'otime'=>time()
        ];
        $res = Db::table('s75_orders')->where('cid',$id)->where('uid',$uid)->find();
        if($res){
                $sta = Db::table('s75_orders')->where('cid',$id)->where('status',1)->where('uid',$uid)->find();
                if($sta){
                    $info['status'] = 'false';
                    $info['info'] = '你已购买过啦,不需要加入购物车';
                }else{
                     $info['status'] = 'false';
                     $info['info'] = '你已加入购物车';
                }
        }else{
              $result = Db::table('s75_orders')->insert($data); 
              if($result>0) {
                $info['status'] = 'true';
                $info['info'] = '加入购物车成功';
              }else{
                $info['status'] = 'false';
                $info['info'] = '加入购物车失败';
              }
        }
        return json($info);
    }
}
